package cn.zwx.common.rocket.producer.support;

import cn.zwx.common.rocket.producer.annotation.RocketTransactionListener;
import cn.zwx.common.rocket.producer.bo.TransactionListenerBO;
import cn.zwx.common.rocket.producer.constants.RocketProducerConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;


/**
 * @author zhangwenxue
 */
@Component
public class RocketTransactionPostProcessor implements BeanPostProcessor {

    private static final Logger logger = LoggerFactory.getLogger(RocketTransactionPostProcessor.class);

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        if (clazz.isAnnotationPresent(RocketTransactionListener.class)){
            if (bean instanceof TransactionListener){
                RocketTransactionListener annotation = clazz.getAnnotation(RocketTransactionListener.class);
                String topic = annotation.topic();
                if (StringUtils.isBlank(topic)){
                    logger.error("not setting TransactionCheckListener topic property,please check annotation config beanName:{}",beanName);
                    return bean;
                }
                TransactionListener checkListener = (TransactionListener) bean;
                TransactionListenerBO listenerBO = new TransactionListenerBO();
                // 设置 checkListener
                listenerBO.setTransactionListener(checkListener);
                listenerBO.setTopic(topic);
                RocketProducerConstants.TRANSACTION_LISTENER_LIST.add(listenerBO);
            }
        }
        return bean;
    }
}
